package fx.mine.active;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONPath;
import com.dtflys.forest.Forest;
import com.dustinredmond.fxtrayicon.FXTrayIcon;
import fx.mine.active.component.MainContainer;
import fx.mine.active.component.music.SliderContainer;
import fx.mine.active.component.music.api.MusicApi;
import fx.mine.active.util.CacheUtil;
import fx.mine.active.util.GlobalConfigUtils;
import javafx.application.Application;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import lombok.extern.log4j.Log4j2;

@Log4j2
public class ActiveApplication extends Application {

    public static void main(String[] args) {
        Application.launch();
    }

    @Override
    public void start(Stage stage) throws Exception {
        Parent parent = new MainContainer(stage);
        Scene scene = new Scene(parent);
//        scene.getStylesheets().add(getClass().getResource("/css/main.css").toExternalForm());

        stage.setScene(scene);
        stage.initStyle(StageStyle.TRANSPARENT);
        stage.setTitle("Life Active");
        new FXTrayIcon.Builder(
                stage, new Image(
                getClass()
                        .getResource("/icon/activeLogo.png")
                        .toExternalForm()))
                .menuItem("Menu1", event -> {
                    log.info("you click menu1");
                })
                .addExitMenuItem("quit")
                .show()
                .build();
        stage.show();
    }

    public ActiveApplication() {
        super();
    }

    @Override
    public void init() throws Exception {
        //音乐服务进行游客登录 并缓存下来 其 cookie
        try {
            MusicApi client = Forest.client(MusicApi.class);
            String cookies;
            GlobalConfigUtils.ConfigBean.Mock mock = GlobalConfigUtils.CONFIG_BEAN.getMock();
            if (mock.isUseMock()) {
                cookies = mock.getCookies();
            } else {
                cookies = client.queryCookies();
            }
            cookies = (String) JSONPath.eval(JSON.parseObject(cookies),"$.cookie");
            log.info("cookies = {}", cookies);
            CacheUtil.cache("music.cookies", cookies);
            String hotStr = client.queryHot(cookies);
            log.info(hotStr);
            CacheUtil.cache("music.hotStr", hotStr);
        } catch (Exception e) {
            log.error("音乐服务不可用");
        }
        log.info("mine music init ...");
    }

    @Override
    public void stop() throws Exception {
        SliderContainer.getExecutors().cancel();
        System.exit(0);
        log.info("mine music stop ...");
    }
}
